package com.yueshop.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.yueshop.auth.feign.MemberFeignService;
import com.yueshop.auth.feign.ThirdPartFeignService;
import com.yueshop.common.constant.AuthConstant;
import com.yueshop.common.exception.BizCodeEnum;
import com.yueshop.common.utils.R;
import com.yueshop.common.utils.SmsCodeUtils;
import com.yueshop.auth.vo.UserLoginVo;
import com.yueshop.auth.vo.UserRegistVo;
import com.yueshop.common.vo.MemberRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    MemberFeignService memberFeignService;



    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){

        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
                //如果验证码已经存在,判断该验证码存入的时间与当前时间 相比较 是否小于60秒
                if(System.currentTimeMillis()-Long.parseLong(redisCode.split("_")[1])<60000){
                    return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
                }
        }
        String code = SmsCodeUtils.randomCode();
        //redis中存入验证码   key sms:code:185128xxx value  验证码_存入验证码的时间
        stringRedisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }



    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult result, RedirectAttributes redirectAttributes){
        //判断是否有错误信息
        if(result.hasErrors()){
            //拿到错误信息 封装为一个map集合
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.yueshop.com/reg.html";
            //return "forward:/reg.html";
        }
        //用户发送请求--->regist[post] --->转发reg.html(默认的路径是get方式)
        //数据校验没有问题, 调用远程服务进行注册
         String code = userRegistVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());

        if(!StringUtils.isEmpty(s)){ //redis验证码不为空 手机已经发送过验证码并且没有过期
            //redis中验证码与页面提交的验证码是否一致   redis vlaue 格式  验证码_系统时间
            if(code.equalsIgnoreCase(s.split("_")[0])){
                //注册
                //校验成功  删除redis验证码
                stringRedisTemplate.delete("AuthConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone()");
                R r = memberFeignService.regist(userRegistVo);
                if(r.getCode()==0){
                    //远程调用注册服务成功了
                    return "redirect:http://auth.yueshop.com/login.html";
                }else{
                    //远程服务注册失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData(new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    //注册成功重定向到 登录页或者首页
                    return "redirect:http://auth.yueshop.com/reg.html";
                }

            }else{
                //手机还没有发送验证码,或者 验证码过期了
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                //注册成功重定向到 登录页或者首页
                return "redirect:http://auth.yueshop.com/reg.html";

            }
        }else{
            //手机还没有发送验证码,或者 验证码过期了
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //注册成功重定向到 登录页或者首页
            return "redirect:http://auth.yueshop.com/reg.html";
        }
    }




    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session){
        //进行远程调用 登录
        R r = memberFeignService.login(userLoginVo);

        if(r.getCode()==0){
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthConstant.LOGIN_USER,data);
            return  "redirect:http://yueshop.com";
        }else{
            //手机还没有发送验证码,或者 验证码过期了
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors",errors);
            //注册成功重定向到 登录页或者首页
            return "redirect:http://auth.yueshop.com/login.html";
        }

    }

    @GetMapping("/login.html")
    public String toLoginPage(HttpSession session){
        Object loginUser = session.getAttribute(AuthConstant.LOGIN_USER);
        if(loginUser==null){
            //未登录 转到登录页面
            return "login";
        }else {
            return "redirect:http://yueshop.com";
        }
    }



}
